package com.bw.zzy.partal2.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.bw.zzy.partal2.db.dao.DoctorDao;
import com.bw.zzy.partal2.db.dao.MedicalDeptSubDoctorDao;
import com.bw.zzy.partal2.exception.GlobalException;
import com.bw.zzy.partal2.pojo.Doctor;
import com.bw.zzy.partal2.pojo.MedicalDeptSubDoctor;
import com.bw.zzy.partal2.service.DoctorService;
import com.bw.zzy.partal2.utils.PageUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class DoctorServiceImpl implements DoctorService {

    @Autowired
    private DoctorDao doctorDao;

    @Autowired
    private MedicalDeptSubDoctorDao medicalDeptSubDoctorDao;



    @Override
    public PageUtils selectConditionByPage(Map param) {
        ArrayList<HashMap> list = null;
        long count = doctorDao.selectConditionByPageCount(param);
        if (count > 0) {
            list = doctorDao.selectConditionByPage(param);
        } else {
            list = new ArrayList<>();
        }
        /*
        * 创建一个分页对象，并且返回
        * */
        int page = MapUtil.getInt(param, "page");
        int length = MapUtil.getInt(param, "length");
        PageUtils pageUtils = new PageUtils(list, count, page, length);
        return pageUtils;
    }

    @Override
    public HashMap selectDoctorDetailById(int id) {
        HashMap hashMap = doctorDao.selectDoctorDetailById(id);


        //tag从数据库查询是一个字符串，要将字符串转换成JSON数组，重新替换tag为JSON格式
        hashMap.replace("tag", JSONUtil.parseArray(MapUtil.getStr(hashMap, "tag")));
        return hashMap;
    }

    @Override
    public void insert(Map param) {
        Doctor doctor = BeanUtil.toBean(param, Doctor.class);
        doctorDao.insert(doctor);

        //根据uuid查询记录到medical_dept_sub_doctor表
        String uuid = doctor.getUuid();
        Integer doctorId = doctorDao.selectIdByUUID(uuid);

        //
        Integer subId = MapUtil.getInt(param, "subId");
        MedicalDeptSubDoctor medicalDeptSubDoctor = new MedicalDeptSubDoctor();
        medicalDeptSubDoctor.setDoctorId(doctorId);
        medicalDeptSubDoctor.setDeptSubId(subId);
        medicalDeptSubDoctorDao.insert(medicalDeptSubDoctor);

    }


    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.access-key}")
    private String accessKey;

    @Value("${minio.secret-key}")
    private String secreKey;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @Override
    public void updatepicture(MultipartFile file, Integer doctorId) {
        String filename = "doctor-" + doctorId + ".jpg";
        /*
         * 通过MinioClient操作Minio图片服务器
         * */

        //根据参数将minioClient实例化
        MinioClient minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secreKey).build();
        try {
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName)
                    //保存的路径  保存在minio里的doctor文件夹
                    .object("doctor/" + filename)
                    //获取输入流，让minio里写
                    .stream(file.getInputStream(), -1, 5 * 1024 * 1024)
                    //图片的类型
                    .contentType("image/jpeg").build());

            //更新数据库的信息
            doctorDao.updatePicture(new HashMap() {{
                put("id", doctorId);
                //放在minio中的doctor文件夹里
                put("photo", "/doctor/" + filename);
            }});

        } catch (ErrorResponseException e) {
            log.error("照骗更新失败");
            e.printStackTrace();
        } catch (Exception e) {
            throw new GlobalException("照骗更新失败");
        }
    }

    @Override
    public HashMap selectById(int id) {
        HashMap hashMap = doctorDao.selectById(id);
        if (hashMap != null) {
            String tag = (String) hashMap.get("tag"); //转换格式前端好显示，不然就是一行
            if (tag != null && !tag.isEmpty()) {

                try {
                    JSONArray array = JSONUtil.parseArray(tag);
                    hashMap.put("tag", array);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return hashMap;
    }

    @Override
    @Transactional
    public void update(Map map) {
        doctorDao.update(map);
        map = MapUtil.renameKey(map, "id", "doctorId");  //前端传过来的是id，查询需要的是doctorId  ,不修改的话，将xml修改成#{id}即可，不用#{doctorId}

        medicalDeptSubDoctorDao.updateDoctorOrSubDept(map);
    }

    @Override
    @Transactional
    public void deleteDoctorByIds(Integer[] ids) {
        doctorDao.deleteDoctorById(ids);
        medicalDeptSubDoctorDao.deleteByDoctorsIds(ids);

    }


    @Override
    public ArrayList<HashMap> selectDoctorBySubId(int subId) {
        return doctorDao.selectDoctorBySubId(subId);
    }
}
